package com.zms.remoteclipboard;

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class RemoteClipboard {

    public static String content = null;

    public static void main(String[] args) throws Exception {
        final String address = "228.5.6.115";
        final int port = 6789;
        final InetAddress group = InetAddress.getByName(address);
        final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        final MulticastSocket socket = new MulticastSocket(port);
        socket.joinGroup(group);
        Thread thread = new Thread() {
            public void run() {
                byte[] buf = new byte[30000];
                DatagramPacket recv = new DatagramPacket(buf, buf.length);
                try {
                    while (System.currentTimeMillis() > 0) {
                        socket.receive(recv);
                        String s = new String(buf, recv.getOffset(), recv.getLength());
                        if (content == null || !content.equals(s)) {
                            System.out.println("set!!");
                            content = s;
                            StringSelection sel = new StringSelection(s);
                            clipboard.setContents(sel, sel);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };
        thread.setDaemon(true);
        thread.start();
        thread = new Thread() {
            public void run() {
                while (System.currentTimeMillis() > 0) {
                    try {
                        if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
                            try {
                                String s = (String) clipboard.getData(DataFlavor.stringFlavor);
                                if (content == null || !content.equals(s)) {
                                    System.out.println("changed!!");
                                    content = s;
                                    byte[] bytes = s.getBytes();
                                    DatagramPacket hi = new DatagramPacket(bytes, bytes.length, group, port);
                                    socket.send(hi);

                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
        System.in.read();
        socket.leaveGroup(group);
    }
}
